package com.situ.mall.controller.back;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.springframework.context.expression.MapAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.situ.mall.common.ServerResponse;

@Controller
@RequestMapping(value="upload")
public class UploadController {

	@RequestMapping(value="/uploadImg")
	@ResponseBody
	public ServerResponse uploadImg(MultipartFile file) {
		String fileName = upload(file);
		
		return ServerResponse.createSuccess("上传成功", fileName);
		
	}

	@RequestMapping(value="/uploadImgByEditor")
	@ResponseBody
	public Map<String, Object> uploadImgByEditor(MultipartFile file) {
		String fileName = upload(file);
		
		String url = "/uploadimg/" + fileName;
		Map<String, Object> map = new HashMap<>();
		map.put("error", 0);
		map.put("msg", "上传成功");
		map.put("url", url);
		return map;
	}
	
	private String upload(MultipartFile file) {
		//防止文件重名，生成 一个不重复随机的名字,并且去掉 "-"
		//342432b432hb4uh234bu2h4v212312(32位)
		String name = UUID.randomUUID().toString().replace("-", "");
		//拿到文件原先的后缀jpg,png
		String extension = FilenameUtils.getExtension(file.getOriginalFilename());
		//合并234143242sfddfs.jpg
		String fileName = name + "." + extension;
		//保存文件到指定目录
		String filePath = "D:\\uploadimg\\" + fileName;
		
		try {
			file.transferTo(new File(filePath)); //图片上传进去
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}	
}
